import Taro from '@tarojs/taro'
import {WX_USER_INFO, USER_MAP_PIN, USER_MONEY, MONEY_HISTORY, USER_CHECKIN} from '../constants/user'
// 从存储中读取openid
const openid = Taro.getStorageSync('openid')
// 从存储中读取token
const token = Taro.getStorageSync('token')
// 从存储中读取位置
let location = Taro.getStorageSync('userPinLocation')
// 从存储中读取userinfo
const userInfo = Taro.getStorageSync('userInfo')
const {avatarUrl: avatar, nickName: nickname} = userInfo

const now = new Date()
const date = `${now.getFullYear()}${('0' + (now.getMonth() + 1)).slice(-2)}${('0' + now.getDate()).slice(-2)}`
const checkined = Taro.getStorageSync('checkin' + date) // 今天是否设置过签到

try {
  location = JSON.parse(location)
} catch (e) {
  location = { // 用户选择的地理位置
    address: null,
    latitude: null,
    longitude: null,
    name: null
  }
}
// 用户信息
const INITIAL_STATE = {
  origin: 'https://fruit.fufruit.cn', // 域名
  openid, // 用户的openid
  token, // 用户的token
  avatar, // wx.getUserInfo 获取到的头像
  nickname, // wx.getUserInfo 获取到的昵称
  money: null, // 用户余额
  name:'', // 用户名
  phone:'', // 用户电话
  location, // 用户选择的地理位置
  money_history: [], // 余额使用记录
  money_history_page: 1, // 余额使用记录页码
  checkin: false // 是否可以签到
}

export default function user (state = INITIAL_STATE, action) {
  switch (action.type) {
    case WX_USER_INFO:
      return {
        ...state,
        ...action.data // 包含 avatarUrl, nickName
      }
    // 设置定位
    case USER_MAP_PIN:
      return {
        ...state,
        location: action.location
      }
    // 用户余额
    case USER_MONEY:
      return {
        ...state,
        money: action.money,
        name: action.name,
        phone: action.phone
      }
    // 余额记录
    case MONEY_HISTORY:
      return {
        ...state,
        money_history: action.money_history,
        money_history_page: action.money_history_page
      }
    // 签到
    case USER_CHECKIN:
      return {
        ...state,
        checkin: checkined === '1' ? false : action.checkin
      }
     default:
       return state
  }
}
